package com.portal.sso.whitelist.server;

import com.portal.sso.core.config.RespoingModelEnum;
import com.portal.sso.core.config.SsoConfig;
import com.portal.sso.core.exception.WhitelistException;
import com.portal.sso.core.server.AbstractTokenManage;
import com.portal.sso.whitelist.config.WhitelistConfig;
import com.portal.sso.whitelist.server.WhitelistModelServer;
import lombok.AllArgsConstructor;

@AllArgsConstructor
public class WhitelistServer extends AbstractTokenManage {

    WhitelistModelServer whitelistModelServer;

    @Override
    public String GetSecret(String appId) throws WhitelistException {
        if (whitelistModelServer.getRedisTemplate().opsForHash().hasKey(WhitelistConfig.WHITELIST_APP_PREFIX + appId, WhitelistConfig.WHITELIST_APP_SECRET)) {
            Object obj = whitelistModelServer.getRedisTemplate().opsForHash().get(WhitelistConfig.WHITELIST_APP_PREFIX + appId, WhitelistConfig.WHITELIST_APP_SECRET);
            if (obj != null) {
                return obj.toString();
            }
        }
        return null;
    }

    @Override
    public boolean CheckAppId(String appId, String server) {
        if (whitelistModelServer.getRedisTemplate().opsForHash().hasKey(WhitelistConfig.WHITELIST_APP_PREFIX + appId, WhitelistConfig.WHITELIST_APP_WHITELIST)) {
            Object obj = whitelistModelServer.getRedisTemplate().opsForHash().get(WhitelistConfig.WHITELIST_APP_PREFIX + appId, WhitelistConfig.WHITELIST_APP_WHITELIST);
            if (obj != null) {
                return obj.toString().contains(server);
            }
        }
        return false;
    }

    @Override
    public String GetUriStyle(String appId) {
        if (whitelistModelServer.getRedisTemplate().opsForHash().hasKey(WhitelistConfig.WHITELIST_APP_PREFIX + appId, WhitelistConfig.WHITELIST_APP_STYLE)) {
            Object obj = whitelistModelServer.getRedisTemplate().opsForHash().get(WhitelistConfig.WHITELIST_APP_PREFIX + appId, WhitelistConfig.WHITELIST_APP_STYLE);
            if (obj != null) {
                return obj.toString();
            }
        }
        return SsoConfig.SSO_REQUEST_URI_TYPE_REST;
    }

    @Override
    public RespoingModelEnum GetRepModel(String appId) {
        if (whitelistModelServer.getRedisTemplate().opsForHash().hasKey(WhitelistConfig.WHITELIST_APP_PREFIX + appId, WhitelistConfig.WHITELIST_APP_MODEL)) {
            Object obj = whitelistModelServer.getRedisTemplate().opsForHash().get(WhitelistConfig.WHITELIST_APP_PREFIX + appId, WhitelistConfig.WHITELIST_APP_MODEL);
            if (obj != null) {
                if(obj.toString().equals(SsoConfig.SSO_RESPONSE_MODEL_WEB)){
                    return RespoingModelEnum.WEB;
                }else {
                    return  RespoingModelEnum.JSON;
                }
            }
        }
        return RespoingModelEnum.WEB;
    }
}
